package com.we823.project.controller.report;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.we823.project.common.file.TaskReportUtil;
import com.we823.project.core.web.WebConstants;
import com.we823.project.model.StationModel;
import com.we823.project.model.UserModel;
import com.we823.project.model.UserStationModel;
import com.we823.project.model.product.PlanDetailModel;
import com.we823.project.model.product.PlanModel;
import com.we823.project.model.product.ProductTaskModel;
import com.we823.project.repository.service.StationService;
import com.we823.project.repository.service.UserService;
import com.we823.project.repository.service.UserStationService;
import com.we823.project.repository.service.product.PlanDetailService;
import com.we823.project.repository.service.product.PlanService;
import com.we823.project.repository.service.product.ProductTaskService;
import com.we823.utils.web.CalendarUtil;
import com.we823.utils.web.RequestUtil;

@Controller
@RequestMapping(WebConstants.REPORT_TASK)
public class TaskReportController extends AbstractBaseReportController<PlanDetailModel> {

	private String baseUrl = WebConstants.REPORT_TASK_TEMPLATE;

	@Autowired
	private PlanService planService;
	@Autowired
	private StationService stationService;

	private @Resource UserStationService userStationService;

	private @Resource UserService userService;
	private @Resource ProductTaskService productTaskService;

	private PlanDetailService planDetailService;

	@Autowired
	public TaskReportController(PlanDetailService planDetailService) {
		super(planDetailService);
		this.planDetailService = planDetailService;
		super.baseUrl = baseUrl;

		setResourceIdentity("report:task");
	}

	@Override
	public Page<PlanDetailModel> getData(PageRequest pageRequest, HttpServletRequest request, Model model, boolean pageable) {
		Page<PlanDetailModel> planDetailPage = null;
		int year = RequestUtil.getValueByParam(request, "year", 0);
		int month = RequestUtil.getValueByParam(request, "month", 0);
		int day = RequestUtil.getValueByParam(request, "day", 0);

		int stationId = RequestUtil.getValueByParam(request, "stationId", 0);
		int userId = RequestUtil.getValueByParam(request, "userId", 0);

		String action = RequestUtil.getValueByParam(request, "action");

		if (!pageable) {
			pageRequest = null;
		}

		if (!"weekly".equals(action)) {
			if (year == 0) {
				if (stationId == 0) {
					planDetailPage = planDetailService.findAll(pageRequest);
				} else {
					if (userId == 0) {
						planDetailPage = planDetailService.findByStationId(stationId, pageRequest);
					} else {
						// 先在productTask中查找所有的planDetail
						Page<ProductTaskModel> productTaskPage = productTaskService.findByUserId(userId, pageRequest);
						List<Integer> planDetailIdList = getPlanDetailIdListFromTasks(productTaskPage);
						planDetailPage = planDetailService.findByIdInAndStationId(planDetailIdList, stationId, pageRequest);
					}
				}

			} else {
				if (stationId == 0) {
					planDetailPage = planDetailService.findByCreateDate(year, month, day, pageRequest);
				} else {
					if (userId == 0) {
						planDetailPage = planDetailService.findByCreateDateAndStationId(year, month, day, stationId, pageRequest);
					} else {
						Page<ProductTaskModel> productTaskPage = productTaskService.findByUserIdAndAddtime(userId, year, month, day, pageRequest);
						List<Integer> planDetailIdList = getPlanDetailIdListFromTasks(productTaskPage);
						if (planDetailIdList != null && planDetailIdList.size() > 0) {
							planDetailPage = planDetailService.findByIdInAndStationId(planDetailIdList, stationId, pageRequest);
						}

					}
				}
			}
		} else { // 按时间段查找
			Date fromDate = RequestUtil.getDateValueByParam(request, "fromDate", "yyyy-MM-dd");
			Date endDate = RequestUtil.getDateValueByParam(request, "endDate", "yyyy-MM-dd");

			if (fromDate != null && endDate != null) {
				long fTime = fromDate.getTime();
				long eTime = fromDate.getTime();
				if (fTime > eTime) {
					Date temp = endDate;
					endDate = fromDate;
					fromDate = temp;
				}

				if (stationId == 0) {
					planDetailPage = planDetailService.findByCreateDateBetween(fromDate, endDate, pageRequest);
				} else {
					if (userId == 0) {
						planDetailPage = planDetailService.findByCreateDateBetweenAndStationId(fromDate, endDate, stationId, pageRequest);
					} else {
						Page<ProductTaskModel> productTaskPage = productTaskService.findByUserIdAndAddtimeBetween(userId, fromDate, endDate, pageRequest);
						List<Integer> planDetailIdList = getPlanDetailIdListFromTasks(productTaskPage);
						if (planDetailIdList != null && planDetailIdList.size() > 0) {
							planDetailPage = planDetailService.findByIdInAndStationId(planDetailIdList, stationId, pageRequest);
						}
					}
				}
			}

		}

		fillInfo(planDetailPage);
		return planDetailPage;
	}

	/**
	 * 从task中获取计划详单
	 * 
	 * @param productTaskPage
	 * @return
	 */
	private List<Integer> getPlanDetailIdListFromTasks(Page<ProductTaskModel> productTaskPage) {
		if (productTaskPage != null) {
			List<ProductTaskModel> productTaskModels = productTaskPage.getContent();
			return getPlanDetailIdListFromTasks(productTaskModels);
		}
		return null;
	}

	private List<Integer> getPlanDetailIdListFromTasks(List<ProductTaskModel> productTaskModels) {
		if (productTaskModels != null && productTaskModels.size() > 0) {
			List<Integer> planDetailIdList = Lists.newArrayList();
			for (ProductTaskModel productTaskModel : productTaskModels) {
				planDetailIdList.add(productTaskModel.getPlanDetailId());
			}

			return planDetailIdList;
		}
		return null;
	}

	@Override
	protected Sort getSort(HttpServletRequest request) {
		Sort sort = super.getSort(request);
		if (sort == null) {
			sort = new Sort(Direction.DESC, "addtime");
		}
		return sort;
	}

	@RequestMapping("getUser")
	@ResponseBody
	public Model getUser(HttpServletRequest request, Model model) {
		int stationId = RequestUtil.getValueByParam(request, "stationId", 0);
		if (stationId > 0) {
			List<UserStationModel> userStationModels = userStationService.findByStationId(stationId);
			if (userStationModels != null && userStationModels.size() > 0) {
				List<Integer> userIdList = Lists.newArrayList();
				for (UserStationModel userStationModel : userStationModels) {
					userIdList.add(userStationModel.getUserId());
				}
				if (userIdList != null && userIdList.size() > 0) {
					List<UserModel> userModels = userService.findByIdIn(userIdList);
					model.addAttribute("users", userModels);
				}
			}
		}

		return model;
	}

	private void fillInfo(Page<PlanDetailModel> planDetailPage) {
		if (planDetailPage != null && planDetailPage.hasContent()) {
			List<PlanDetailModel> planDetailModels = planDetailPage.getContent();
			if (planDetailModels != null && planDetailModels.size() > 0) {
				Map<Integer, PlanModel> planMap = planService.map();
				for (PlanDetailModel planDetailModel : planDetailModels) {
					if (planMap.containsKey(planDetailModel.getPlanId())) {
						PlanModel planModel = planMap.get(planDetailModel.getPlanId());
						planDetailModel.setPlan(planModel);
						planDetailModel.setPlanCode(planModel.getCode());
					}
				}

				Map<Integer, StationModel> stationMap = stationService.map();
				List<Integer> planDetailIdList = Lists.newArrayList();
				for (PlanDetailModel planDetailModel : planDetailModels) {
					int stationId = planDetailModel.getStationId();
					planDetailIdList.add(planDetailModel.getId());
					if (stationMap.containsKey(stationId)) {
						StationModel stationModel = stationMap.get(stationId);
						if (stationModel != null) {
							planDetailModel.setStation(stationModel);
							planDetailModel.setStationName(stationModel.getName());
						} else {
							planDetailModel.setStationName("未知");
						}

					}
				}
				if (planDetailIdList != null && planDetailIdList.size() > 0) {
					List<ProductTaskModel> productTaskModels = productTaskService.findByPlanDetialIdIn(planDetailIdList);

					Map<Integer, String> planDetailRealnameMap = Maps.newHashMap();
					Map<Integer, ProductTaskModel> planDetailTaskMap = Maps.newHashMap();
					if (productTaskModels != null && productTaskModels.size() > 0) {
						Map<Integer, UserModel> userMap = userService.map();
						for (ProductTaskModel productTaskModel : productTaskModels) {

							planDetailTaskMap.put(productTaskModel.getPlanDetailId(), productTaskModel);
							UserModel userModel = userMap.get(productTaskModel.getUserId());
							if (userModel != null) {
								if (!org.apache.commons.lang3.StringUtils.isEmpty(userModel.getRealname())) {
									planDetailRealnameMap.put(productTaskModel.getPlanDetailId(), userModel.getRealname());
								} else {
									planDetailRealnameMap.put(productTaskModel.getPlanDetailId(), userModel.getUsername());
								}
							}
						}
					}

					if (planDetailRealnameMap.size() > 0) {
						for (PlanDetailModel planDetailModel : planDetailModels) {
							int planDetailId = planDetailModel.getId();
							planDetailModel.setRealname(planDetailRealnameMap.get(planDetailId));

							ProductTaskModel productTaskModel = planDetailTaskMap.get(planDetailId);
							if (productTaskModel != null) {
								planDetailModel.setTaskCode(productTaskModel.getCode());
								planDetailModel.setCountTime(productTaskModel.getCountTime());
							}
						}
					}
				}
			}
		}

	}

	public PlanService getPlanService() {
		return planService;
	}

	public void setPlanService(PlanService planService) {
		this.planService = planService;
	}

	public StationService getStationService() {
		return stationService;
	}

	public void setStationService(StationService stationService) {
		this.stationService = stationService;
	}

	@Override
	public void expendInfo(Model model) {
		List<StationModel> stationModels = stationService.findAll();
		model.addAttribute("stations", stationModels);

		CalendarUtil calendarUtil = new CalendarUtil();
		String monday = calendarUtil.getMondayOFWeek();
		String today = CalendarUtil.convertDateToString(new Date(), CalendarUtil.YMD);
		model.addAttribute("monday", monday);
		model.addAttribute("today", today);
	}

	@Override
	public boolean export(String fullname, String sheetname, List<PlanDetailModel> models) {
		TaskReportUtil taskReportUtil = new TaskReportUtil();
		return taskReportUtil.createExcel2007(fullname, sheetname, models);
	}

}
